//
//  JSTCommonCenterView.m
//  KYKJPackDemo
//
//  Created by 01 on 17/5/17.
//  Copyright © 2017年 ???. All rights reserved.
//

#import "JSTCommonCenterView.h"
#import "MessageView.h"

#define showKeyboard 216

#define durationTime 0.25

@interface JSTCommonCenterView ()<MessageViewDelegate, UITextViewDelegate>

//分割线
@property (nonatomic, strong) UIView *sepView;

//父视图
@property (nonatomic,strong)UIView *superView;

//覆盖的视图
@property (nonatomic, strong) UIButton *hideBtn;

//placeLabel
@property (nonatomic, strong) UILabel *placeLabel;

@property (nonatomic,strong)MessageView *messageView;

@end

@implementation JSTCommonCenterView

-(id)initWithFrame:(CGRect)frame andOwner:(id)owner
{
    self = [super initWithFrame:frame andOwner:owner];
    
    if (self) {
        
        self.backgroundColor = kANGBackgoundColor;
        
        self.frame = CGRectMake(0, CGRectGetMinY(frame), kDeviceWidth, CGRectGetHeight(frame));
        
        _sepView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, 0.5)];
        _sepView.backgroundColor = kANGSeparateLineColor;
        [self addSubview:_sepView];
        
        //初始化为NO
        self.keyboardIsShow=NO;
        //父视图
        _superView=owner;
        
        [self addSubview:self.showBtn];
        
        [self addSubview:self.comTextView];
        
        [self addSubview:self.sendBtn];
        
        self.messageView.tag=10003;
        //注册键盘通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    }
    return self;
}

#pragma mark - 覆盖视图

- (void) createCoverView:(BOOL )isCreate
{
    if (isCreate) {
        [self addSubview:self.hideBtn];
    }
}

- (UIButton *) hideBtn
{
    if (!_hideBtn) {
        _hideBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _hideBtn.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        [_hideBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_showBtn.frame)+kCurrentScreenWidth(5), kCurrentScreenWidth(6), kDeviceWidth-CGRectGetMaxX(_showBtn.frame)-kCurrentScreenWidth(15)-kCurrentScreenWidth(5), kCurrentScreenWidth(32))];
        label.backgroundColor = kANGBackgoundColor;
        label.layer.cornerRadius = kCurrentScreenWidth(5);
        label.layer.borderWidth = 0.5;
        label.layer.masksToBounds = YES;
        
        label.layer.borderColor = [UIColor colorWithHexString:@"9fa0a0"].CGColor;
        
        label.font = kSystemFont(kCurrentScreenWidth(16));
        label.textColor = [UIColor colorWithHexString:@"9fa0a0"];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = @"仅好友可评论";
        [_hideBtn addSubview:label];
    }
    return _hideBtn;
}

- (void) btnClick:(UIButton *)btn
{
    
    if (_delegate&&[_delegate respondsToSelector:@selector(isAllowCommentWithCommonCenterView:)]) {
        [_delegate isAllowCommentWithCommonCenterView:@"仅好友可评论"];
    }
}

-(void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    _originalFrame = frame;
}
//_originalFrame的set方法  因为会调用setFrame  所以就不在此做赋值；
-(void)setOriginalFrame:(CGRect)originalFrame
{
    self.frame = CGRectMake(0, CGRectGetMinY(originalFrame), 320, CGRectGetHeight(originalFrame));
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
    
    
}

#pragma mark get方法实例化输入框／btn/messageView
-(UIButton *)showBtn
{
    if (!_showBtn) {
        _showBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_showBtn setFrame:CGRectMake(5, 0, self.frame.size.height, self.frame.size.height)];
        [_showBtn setImage:[UIImage imageNamed:@"healthy_comments_face"] forState:UIControlStateNormal];
        [_showBtn setImage:[UIImage imageNamed:@"healthy_icon_keyboard"] forState:UIControlStateSelected];
        [_showBtn addTarget:self action:@selector(showBtnPress:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _showBtn;
}

-(UITextView *)comTextView
{
    if (!_comTextView) {
        _comTextView=[[UITextView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_showBtn.frame)+kCurrentScreenWidth(5), kCurrentScreenWidth(6), kDeviceWidth-CGRectGetMaxX(_showBtn.frame)-kCurrentScreenWidth(5)-kCurrentScreenWidth(60), kCurrentScreenWidth(32))];
        _comTextView.delegate=self;
        _comTextView.font= kSystemFont(kCurrentScreenWidth(12));
        _comTextView.textColor = [UIColor colorWithHexString:@"000000"];
        _comTextView.layer.cornerRadius=kCurrentScreenWidth(5);
        _comTextView.layer.borderWidth= 0.5;
        
        _comTextView.layer.borderColor=[UIColor colorWithHexString:@"9fa0a0"].CGColor;
        
        _placeLabel = [[UILabel alloc] initWithFrame:CGRectMake(kCurrentScreenWidth(7), 0, _comTextView.frame.size.width - kCurrentScreenWidth(7), _comTextView.frame.size.height)];
        _placeLabel.font = kSystemFont(kCurrentScreenWidth(15));
        _placeLabel.textColor = [UIColor colorWithHexString:@"9fa0a0"];
        _placeLabel.text = @"匿名评价";
        [_comTextView addSubview:_placeLabel];
    }
    return _comTextView;
}

-(UIButton *)sendBtn
{
    if (!_sendBtn) {
        _sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_sendBtn setFrame:CGRectMake(CGRectGetMaxX(_comTextView.frame), 0, self.frame.size.height+kCurrentScreenWidth(15), self.frame.size.height)];
        //        [_sendBtn setFrame:CGRectMake(self.frame.size.width - self.frame.size.height, 0, self.frame.size.height, self.frame.size.height)];
        
        [_sendBtn addTarget:self action:@selector(sendBtnPress:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc] initWithFrame:_sendBtn.bounds];
        label.text = @"发布";
        label.textAlignment = NSTextAlignmentCenter;
        [_sendBtn addSubview:label];
        
    }
    return _sendBtn;
}

-(MessageView *)messageView
{
    if (!_messageView) {
        _messageView=[[MessageView alloc] initWithFrame:CGRectMake(0, kDeviceHeight-kNavBarHeight, kDeviceWidth, showKeyboard)];
        _messageView.delegate=self;
        [self.superView addSubview:_messageView];
    }
    return _messageView;
}


#pragma mark selfDelegate method
//发送按钮
-(void)sendBtnPress:(UIButton*)sender
{
    self.showBtn.selected=NO;
    [UIView animateWithDuration:durationTime animations:^{
        _messageView.frame=CGRectMake(0, kDeviceHeight, kDeviceWidth, 216);
        CGRect frame=_comTextView.frame;
        frame.size.height=kCurrentScreenWidth(32);
        _comTextView.frame=frame;
        self.frame=CGRectMake(0, kDeviceHeight-kCurrentScreenWidth(44)-kNavBarHeight, kDeviceWidth, kCurrentScreenWidth(44));
    }];
    if (self.delegate&&[self.delegate respondsToSelector:@selector(inputBar:sendBtnPress:withInputString:)]) {
        [self.delegate inputBar:self sendBtnPress:sender withInputString:self.comTextView.text];
    }
    if (self.clearInputWhenSend) {
        self.comTextView.text = @"";
    }
    if (self.resignFirstResponderWhenSend) {
        [self resignFirstResponder];
    }
    
    //显示与隐藏
    if (IsStrEmpty(self.comTextView.text)) {
        _placeLabel.hidden = NO;
    } else {
        _placeLabel.hidden = YES;
    }
}
//表情按钮
-(void)showBtnPress:(UIButton *)shower
{
    shower.selected=!shower.selected;
    
    if (shower.selected) {
        [self.comTextView resignFirstResponder];
        
        [UIView animateWithDuration:durationTime animations:^{
            _messageView.frame=CGRectMake(0, kDeviceHeight-showKeyboard-kNavBarHeight, kDeviceWidth, showKeyboard);
            
            
            CGRect selfFram=self.frame;
            
            selfFram.origin.y=kDeviceHeight-kNavBarHeight-showKeyboard-selfFram.size.height;
            self.frame=selfFram;
        }];
    } else {
        _messageView.frame=CGRectMake(0, kDeviceHeight-kNavBarHeight, kDeviceWidth, 216);
        [self.comTextView becomeFirstResponder];
        
    }
    
    
}

#pragma mark keyboardNotification
-(void)keyboardChange:(NSNotification*)notification
{
    
}

- (void)keyboardWillShow:(NSNotification*)notification
{
    CGRect _keyboardRect = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    self.keyboardFrame=_keyboardRect;
    self.showBtn.selected=NO;
    
    [UIView animateWithDuration:durationTime animations:^
    {
        
        CGRect selfFram=self.frame;
        
        selfFram.origin.y=kDeviceHeight-kNavBarHeight-selfFram.size.height-_keyboardFrame.size.height;
        self.frame=selfFram;
        
    }];
}

- (void)keyboardWillHide:(NSNotification*)notification
{
    //键盘隐藏
    self.keyboardIsShow=NO;
    [UIView animateWithDuration:durationTime animations:^
    {
        CGRect selfFram=self.frame;
        
        selfFram.origin.y=kDeviceHeight-kNavBarHeight-selfFram.size.height;
        
        self.frame=selfFram;
        
        _messageView.frame=CGRectMake(0, kDeviceHeight, kDeviceWidth, showKeyboard);
    }];
}




-(BOOL)resignFirstResponder
{
    [self.comTextView resignFirstResponder];
    return [super resignFirstResponder];
}

#pragma mark ===============代理方法=================
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    //删除
    if (text.length == 0&&[textView.text hasSuffix:@"]"])
    {
        NSMutableString *newString=[NSMutableString stringWithString:textView.text];
        
        //正则表达式
        NSString *patter=@"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]";
        NSError *error=nil;
        NSRegularExpression *regularExpression=[NSRegularExpression regularExpressionWithPattern:patter options:NSRegularExpressionCaseInsensitive error:&error];
        //匹配文字
        NSArray *resultArray=[regularExpression matchesInString:newString options:0 range:NSMakeRange(0, newString.length)];
        NSTextCheckingResult *match=resultArray.lastObject;
        
        [newString deleteCharactersInRange:NSMakeRange(match.range.location, match.range.length - 1)];
        
        textView.text=newString;
    }else
    {
        
    }
    return YES;
}

- (void) textViewDidBeginEditing:(UITextView *)textView
{
    
}

-(void)textViewDidChange:(UITextView *)textView
{
    //显示与隐藏
    if (IsStrEmpty(textView.text)) {
        _placeLabel.hidden = NO;
    } else {
        _placeLabel.hidden = YES;
    }
    
    CGFloat textHeight=0;
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=7)
    {
        CGRect textFrame=[[textView layoutManager] usedRectForTextContainer:[textView textContainer]];
        textHeight=textFrame.size.height;
    } else
    {
        textHeight=textView.contentSize.height;
    }
    
    if (textHeight>kCurrentScreenWidth(32)&&textHeight<100)
    {
        CGRect frame=textView.frame;
        frame.size.height=textHeight+7;
        textView.frame=frame;
        
        CGRect selfFram=self.frame;
        selfFram.size.height=textHeight+7+14;
        selfFram.origin.y=kDeviceHeight-kNavBarHeight-_keyboardFrame.size.height-selfFram.size.height;
        self.frame=selfFram;
    }
    if (textView.contentSize.height<kCurrentScreenWidth(32))
    {
        CGRect frame=textView.frame;
        frame.size.height=kCurrentScreenWidth(32);
        textView.frame=frame;
        
        CGRect selfFram=self.frame;
        selfFram.size.height=kCurrentScreenWidth(44);
        selfFram.origin.y=kDeviceHeight-kNavBarHeight-_keyboardFrame.size.height-selfFram.size.height;
        self.frame=selfFram;
    }
    
    CGRect line=[textView caretRectForPosition:textView.selectedTextRange.start];
    CGFloat overflow=line.origin.y+line.size.height-(textView.contentOffset.y+textView.bounds.size.height-textView.contentInset.bottom-textView.contentInset.top);
    if (overflow>0)
    {
        CGPoint offset=textView.contentOffset;
        offset.y+=overflow+7;
        [textView setContentOffset:offset];
    }
}

- (void) textViewDidEndEditing:(UITextView *)textView
{
    if (IsStrEmpty(textView.text)) {
        _placeLabel.hidden = NO;
    }
}

-(void)messageViewFaceWithButton:(UIButton *)but
{
    if (but.tag > 0) {
        
        NSString *faceName = [[NSString alloc] init];
        NSString *expressstring = [NSString stringWithFormat:@"e_%zd.png",but.tag];
        NSString *plistStr = [[NSBundle mainBundle]pathForResource:@"ANGEmoji" ofType:@"plist"];
        NSDictionary *plistDic = [[NSDictionary  alloc]initWithContentsOfFile:plistStr];
        
        for (int j = 0; j<=[[plistDic allKeys]count]-1; j++)
        {
            if ([[plistDic objectForKey:[[plistDic allKeys]objectAtIndex:j]]
                 isEqualToString:expressstring])
            {
                faceName = [[plistDic allKeys]objectAtIndex:j];
            }
        }
        self.comTextView.text = [self.comTextView.text stringByAppendingString:faceName];
        
    } else {
        //删除表情
        if (self.comTextView.text.length>0) {
            if ([self.comTextView.text hasSuffix:@"]"]) {
                NSMutableString *newString=[NSMutableString stringWithString:self.comTextView.text];
                
                //正则表达式
                NSString *patter=@"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]";
                NSError *error=nil;
                NSRegularExpression *regularExpression=[NSRegularExpression regularExpressionWithPattern:patter options:NSRegularExpressionCaseInsensitive error:&error];
                //匹配文字
                NSArray *resultArray=[regularExpression matchesInString:newString options:0 range:NSMakeRange(0, newString.length)];
                NSTextCheckingResult *match=resultArray.lastObject;
                
                [newString deleteCharactersInRange:match.range];
                
                self.comTextView.text=newString;
                
            } else {
                NSString *newStr=self.comTextView.text;
                self.comTextView.text=[newStr substringToIndex:newStr.length-1];
            }
        }
        
    }
    
    if (IsStrEmpty(self.comTextView.text)) {
        _placeLabel.hidden = NO;
    } else {
        _placeLabel.hidden = YES;
    }
    
    CGFloat textHeight=0;
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=7) {
        CGRect textFrame=[[self.comTextView layoutManager] usedRectForTextContainer:[self.comTextView textContainer]];
        textHeight=textFrame.size.height;
    } else {
        textHeight=self.comTextView.contentSize.height;
    }
    
    if (textHeight>kCurrentScreenWidth(32)&&textHeight<100) {
        CGRect frame=self.comTextView.frame;
        frame.size.height=textHeight+7;
        self.comTextView.frame=frame;
        
        CGRect selfFram=self.frame;
        selfFram.size.height=textHeight+7+14;
        selfFram.origin.y=kDeviceHeight-kNavBarHeight-showKeyboard-selfFram.size.height;
        self.frame=selfFram;
    }
    if (self.comTextView.contentSize.height<kCurrentScreenWidth(32)) {
        CGRect frame=self.comTextView.frame;
        frame.size.height=kCurrentScreenWidth(32);
        self.comTextView.frame=frame;
        
        CGRect selfFram=self.frame;
        selfFram.size.height=kCurrentScreenWidth(44);
        selfFram.origin.y=kDeviceHeight-kNavBarHeight-showKeyboard-selfFram.size.height;
        self.frame=selfFram;
    }
}
@end
